04. Inline-Block
inline-block intro
So far, there's been a distinction between inline and block elements. However, there’s a hybrid of the two!
.example {
display: inline-block;
}
display: inline-block
elements can be sized like block elements but are laid out like inline elements.
Take a look at this example. Notice that the .random
span in the middle of the text has a width and height assigned to it but the span in the resulting website (shown below) acts like a regular inline element - it is rendered as a line-box and the width
and height
are ignored.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Inline-Block Example</title>
<style>
* {
box-sizing: border-box;
font-family: 'Source Sans Pro', sans-serif;
font-weight: bold;
}
.inline-block { /* hasn't been assigned! */
display: inline-block;
}
.random {
border: 2px solid #2e3d49;
background-color: #ecc81a;
width: 20em;
height: 40px;
}
</style>
<link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="container">
<span>...</span>
<span class="random">This is a random span.</span>
<span>...</span>
</div>
</body>
</html>
inline example

Looks like the random span is acting like a normal inline element.
inline block
Now, I'll add .inline-block
to the .random
span. Take a look at the website now to see how it looks!
<span class="random inline-block">This is a random span.</span>
inline-block

Now the random span has a defined width and height and still appears in the same line as the rest of the text!
now with div
You can see that the .random
span is mixing the behavior of a block element and an inline element. But what if display: inline-block
is applied to a block element, like a <div>
?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Inline-Block Example</title>
<style>
* {
box-sizing: border-box;
font-family: 'Source Sans Pro', sans-serif;
font-weight: bold;
}
.inline-block {
display: inline-block;
}
.random {
border: 2px solid #2e3d49;
background-color: #ecc81a;
/* no width this time, but you could certainly apply one */
height: 40px;
}
</style>
<link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="container">
<span>...</span>
<div class="random inline-block">This is a random div.</div>
<div class="random inline-block">This is a second random div.</div>
<span>...</span>
</div>
</body>
</html>
divs acting like spans

Same thing!
end
Regardless of the tag, any element with display: inline-block
takes on the layout behaviors of an inline element with the sizing behaviors of a block element.
Now that you've seen inline-block elements, I want to show you a quirk of HTML that shows up from time to time.